<template>
  <div class="rate-settings-tab">
    <div class="rate-settings-header">
      <h3>费率设置</h3>
      <div>
        <el-button type="primary" @click="openRateSettings">编辑费率</el-button>
      </div>
    </div>

    <!-- 汇率设置 -->
    <el-card class="rate-card">
      <template #header>
        <div class="card-header">
          <span>汇率设置</span>
          <el-tag v-if="member.exchangeRate" type="success" size="small">自定义</el-tag>
          <el-tag v-else type="info" size="small">基础设置</el-tag>
        </div>
      </template>
      <div class="rate-content">
        <div class="rate-value">{{ member.exchangeRate || getDefaultExchangeRate() }}</div>
        <div class="rate-description">基础设置汇率：{{ getDefaultExchangeRate() }}</div>
      </div>
    </el-card>

    <!-- 手续费设置 -->
    <el-card v-if="member.memberType === 'B' || member.memberType === 'C'" class="rate-card">
      <template #header>
        <div class="card-header">
          <span>手续费设置</span>
          <el-tag v-if="member.serviceFee" type="success" size="small">自定义</el-tag>
          <el-tag v-else type="info" size="small">基础设置</el-tag>
        </div>
      </template>
      <div class="rate-content">
        <!-- 如果会员有自定义手续费设置，显示自定义设置 -->
        <div v-if="member.serviceFeeRanges && member.serviceFeeRanges.length > 0" class="rate-value">
          <el-tag type="success" size="small" style="margin-right: 8px;">自定义</el-tag>
          <span style="margin-left: 8px; color: #606266;">已设置分站点分阶段手续费</span>
        </div>

        
        <!-- 说明文字 -->
        <div class="rate-description" style="margin-top: 16px; padding: 12px; background-color: #f5f7fa; border-radius: 4px;">
          <div style="font-size: 13px; color: #606266; line-height: 1.5;">
            <strong>说明：</strong><br>
            • <strong>基础设置</strong>：使用系统预设的分站点分阶段手续费<br>
            • <strong>自定义设置</strong>：会员可自定义分站点分阶段手续费，优先级高于基础设置<br>
            • 手续费按价格区间分段计算，不同站点可设置不同的费率结构
          </div>
        </div>
        
        <!-- 手续费价格区间详情 -->
        <div v-if="member.serviceFeeRanges && member.serviceFeeRanges.length > 0" class="rate-details">
          <h4>自定义分站点分阶段手续费设置：</h4>
          

          
          <!-- 按站点分块显示 -->
          <div v-if="getUniqueSites().length > 0" class="site-fee-blocks">
            <div v-for="site in getUniqueSites()" :key="site" class="site-fee-block">
              <div class="block-header">
                <el-icon class="site-icon"><Service /></el-icon>
                <span class="site-name">{{ site }}</span>
              </div>
              
              <div class="fee-table">
                <div class="table-header">
                  <span class="header-cell">区间类型</span>
                  <span class="header-cell">价格区间</span>
                  <span class="header-cell">手续费</span>
                </div>
                
                <div v-for="(feeItem, index) in getFeesBySite(site)" :key="`${site}-${index}`" class="table-row">
                  <span class="table-cell">
                    <el-tag v-if="feeItem.rangeType === 'system'" type="primary" size="small">系统区间</el-tag>
                    <el-tag v-else type="warning" size="small">自定义区间</el-tag>
                  </span>
                  <span class="table-cell">
                    <span v-if="feeItem.rangeType === 'system'">{{ feeItem.range }}</span>
                    <span v-else>
                      <span v-if="feeItem.minAmount !== null && feeItem.minAmount !== undefined">{{ feeItem.minAmount }}</span>
                      <span v-else>0</span>
                      -
                      <span v-if="feeItem.maxAmount !== null && feeItem.maxAmount !== undefined && feeItem.maxAmount !== ''">{{ feeItem.maxAmount }}</span>
                      <span v-else>以上</span>
                      円
                    </span>
                  </span>
                  <span class="table-cell fee-amount">{{ feeItem.fee }}円</span>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 如果没有站点数据 -->
          <div v-else style="text-align: center; padding: 20px; color: #909399;">
            暂无站点数据
          </div>
        </div>
      </div>
    </el-card>

    <!-- 服务费率设置 -->
    <el-card v-if="member.memberType === 'B'" class="rate-card">
      <template #header>
        <div class="card-header">
          <span>服务费率设置</span>
          <el-tag v-if="member.serviceRate" type="success" size="small">自定义</el-tag>
          <el-tag v-else type="info" size="small">基础设置</el-tag>
        </div>
      </template>
              <div class="rate-content">
          <!-- 如果会员有自定义服务费率，显示自定义值 -->
          <div v-if="member.serviceRate" class="rate-value">
            <el-tag type="success" size="small" style="margin-right: 8px;">自定义</el-tag>
            {{ member.serviceRate }}%
          </div>
          <!-- 否则显示基础设置的分站点服务费率 -->
          <div v-else class="rate-value">
            <el-tag type="info" size="small" style="margin-right: 8px;">基础设置</el-tag>
            <div style="margin-top: 8px;">
              <el-tag v-for="site in getDefaultServiceRateSites()" :key="site.site" size="small" style="margin-right: 4px;">
                {{ site.site }}: {{ site.rate }}%
              </el-tag>
            </div>
          </div>

        
        <!-- 服务费率站点详情 -->
        <div v-if="member.serviceRateSites && member.serviceRateSites.length > 0" class="rate-details">
          <h4>站点费率设置（分站点）：</h4>
          <el-table :data="member.serviceRateSites" border style="width: 100%; margin-top: 8px;">
            <el-table-column prop="site" label="站点" width="150" />
            <el-table-column prop="rate" label="费率" width="120">
              <template #default="{ row }">
                {{ row.rate }}%
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-card>

    <!-- 保证金比例设置 -->
    <el-card v-if="member.memberType === 'B'" class="rate-card">
      <template #header>
        <div class="card-header">
          <span>保证金比例设置</span>
          <el-tag v-if="member.depositRatio" type="success" size="small">自定义</el-tag>
          <el-tag v-else type="info" size="small">基础设置</el-tag>
        </div>
      </template>
              <div class="rate-content">
          <!-- 如果会员有自定义保证金比例，显示自定义值 -->
          <div v-if="member.depositRatio" class="rate-value">
            <el-tag type="success" size="small" style="margin-right: 8px;">自定义</el-tag>
            {{ member.depositRatio }}%
          </div>
          <!-- 否则显示基础设置的分站点保证金比例 -->
          <div v-else class="rate-value">
            <el-tag type="info" size="small" style="margin-right: 8px;">基础设置</el-tag>
            <div style="margin-top: 8px;">
              <el-tag v-for="site in getDefaultDepositRatioSites()" :key="site.site" size="small" style="margin-right: 4px;">
                {{ site.site }}: {{ site.ratio }}%
              </el-tag>
            </div>
          </div>

        
        <!-- 保证金比例站点详情 -->
        <div v-if="member.depositRatioSites && member.depositRatioSites.length > 0" class="rate-details">
          <h4>站点比例设置（分站点）：</h4>
          <el-table :data="member.depositRatioSites" border style="width: 100%; margin-top: 8px;">
            <el-table-column prop="site" label="站点" width="150" />
            <el-table-column prop="ratio" label="比例" width="120">
              <template #default="{ row }">
                {{ row.ratio }}%
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

const router = useRouter();

// 定义props
interface Props {
  member: {
    id: string;
    nickname: string;
    memberType: string;
    exchangeRate?: string | null;
    serviceFee?: string | null;
    serviceFeeRanges?: any[];
    serviceRate?: string | null;
    serviceRateSites?: any[];
    depositRatio?: string | null;
    depositRatioSites?: any[];
  };
}

const props = defineProps<Props>();
const emit = defineEmits<{
  openRateDialog: [member: any]
}>();

import { exchangeRateService } from '@/services/exchangeRateService';
import { baseSettingsService } from '@/services/baseSettingsService';

// 费率设置相关函数
function getDefaultExchangeRate() {
  // 获取基础设置中保存的实际汇率
  const savedActualRate = localStorage.getItem('exchangeRate')
  if (savedActualRate) {
    return parseFloat(savedActualRate).toFixed(4)
  }
  
  // 如果没有保存的实际汇率，则使用汇率服务中的当前汇率
  return exchangeRateService.getCurrentRate()
}

function getDefaultServiceFee(exchangeRate: string) {
  // 根据会员类型获取手续费
  // 这里使用一个示例金额来计算手续费，实际应该根据订单金额计算
  const exampleAmount = 10000 // 示例金额10000円
  if (props.member.memberType === 'B') {
    return baseSettingsService.getServiceFeeForB(exampleAmount).toString()
  } else if (props.member.memberType === 'C') {
    return baseSettingsService.getServiceFeeForC(exampleAmount).toString()
  }
  return '200' // 默认手续费
}

// 获取默认服务费率（按站点）
function getDefaultServiceRate(site?: string) {
  // 只有B类客户有服务费率
  if (props.member.memberType === 'B') {
    const settings = baseSettingsService.getServiceRateSettings()
    if (site) {
      // 如果指定了站点，查找该站点的费率
      const siteSetting = settings.find(s => s.site === site)
      if (siteSetting) {
        return siteSetting.rate.toString()
      }
    }
    // 如果没有指定站点或找不到该站点，返回第一个费率
    if (settings.length > 0) {
      return settings[0].rate.toString()
    }
    return '3.5' // 默认服务费率
  }
  return '0'
}

// 获取默认保证金比例（按站点）
function getDefaultDepositRatio(site?: string) {
  // 只有B类客户有保证金比例
  if (props.member.memberType === 'B') {
    const settings = baseSettingsService.getDepositRateSettings()
    if (site) {
      // 如果指定了站点，查找该站点的比例
      const siteSetting = settings.find(s => s.site === site)
      if (siteSetting) {
        return siteSetting.rate.toString()
      }
    }
    // 如果没有指定站点或找不到该站点，返回第一个比例
    if (settings.length > 0) {
      return settings[0].rate.toString()
    }
    return '10.0' // 默认保证金比例
  }
  return '0'
}

// 获取所有站点的默认服务费率
function getDefaultServiceRateSites() {
  if (props.member.memberType === 'B') {
    const settings = baseSettingsService.getServiceRateSettings()
    return settings.map(s => ({
      site: s.site,
      rate: s.rate
    }))
  }
  return []
}

// 获取所有站点的默认保证金比例
function getDefaultDepositRatioSites() {
  if (props.member.memberType === 'B') {
    const settings = baseSettingsService.getDepositRateSettings()
    return settings.map(s => ({
      site: s.site,
      ratio: s.rate
    }))
  }
  return []
}



// 获取基础设置收费管理页面的费率标签（按图片中的显示方式）
function getDefaultServiceFeeTags() {
  if (props.member.memberType === 'B' || props.member.memberType === 'C') {
    const settings = baseSettingsService.getServiceFeeSettings(props.member.memberType)
    
    // 转换为标签格式：站点:手续费円
    return settings.map(setting => ({
      id: setting.id,
      site: setting.site,
      fee: setting.fee
    }))
  }
  return []
}

// 格式化价格区间显示
function formatPriceRange(minAmount: number | null, maxAmount: number | null): string {
  if (minAmount === null && maxAmount === null) {
    return '全部'
  } else if (minAmount === null) {
    return `0 - ${maxAmount}円`
  } else if (maxAmount === null) {
    return `${minAmount}円以上`
  } else {
    return `${minAmount} - ${maxAmount}円`
  }
}



// 打开费率设置
function openRateSettings() {
  // 直接打开费率设置对话框
  // 这里需要触发父组件的费率设置对话框
  // 通过emit事件通知父组件
  emit('openRateDialog', props.member)
}

// 获取唯一站点列表
function getUniqueSites() {
  if (!props.member.serviceFeeRanges || props.member.serviceFeeRanges.length === 0) {
    return []
  }
  const sites = props.member.serviceFeeRanges.map(item => item.site)
  return [...new Set(sites)]
}

// 根据站点获取手续费设置
function getFeesBySite(site: string) {
  if (!props.member.serviceFeeRanges || props.member.serviceFeeRanges.length === 0) {
    return []
  }
  return props.member.serviceFeeRanges.filter(item => item.site === site)
}
</script>

<style scoped>
.rate-settings-tab {
  padding: 20px;
}

.rate-settings-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.rate-settings-header h3 {
  margin: 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.rate-card {
  margin-bottom: 20px;
}

.rate-card .card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.rate-content {
  padding: 16px 0;
}

.rate-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.rate-description {
  font-size: 14px;
  color: #606266;
  margin-bottom: 16px;
}

.rate-details {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #e4e7ed;
}

.rate-details h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #303133;
  font-weight: 500;
}

/* 按站点分块显示样式 */
.site-fee-blocks {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-top: 16px;
}

.site-fee-block {
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.block-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e4e7ed;
}

.site-icon {
  color: #67c23a;
  font-size: 16px;
}

.site-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.fee-table {
  background: #f8f9fa;
  border-radius: 6px;
  overflow: hidden;
}

.table-header {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  background: #f5f7fa;
  padding: 12px 16px;
  border-bottom: 1px solid #e4e7ed;
}

.header-cell {
  font-size: 13px;
  font-weight: 600;
  color: #606266;
}

.table-row {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  align-items: center;
  background: white;
}

.table-row:last-child {
  border-bottom: none;
}

.table-cell {
  font-size: 14px;
  color: #303133;
}

.fee-amount {
  color: #409EFF;
  font-weight: 500;
}
</style> 